package org.springblade.modules.opcua.kit;

import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.springblade.modules.opcua.model.OpcTargetBean;
import org.springblade.modules.opcua.kit.OpcUaUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 各种缓存
 */
public class WorkCache {

    //客户端缓存
    private static Map<Long, OpcUaClient> clientConfigMap = new HashMap<>();

    /**
     * 取得客户端
     *
     * @param config
     * @return
     */
    public static synchronized OpcUaClient getClient(OpcTargetBean config) {
        OpcUaClient client = clientConfigMap.get(config.getId());
        if (client == null) {
            client = OpcUaUtil.createClient(config.getOpcUrl());
            if (client != null) {
                clientConfigMap.put(config.getId(), client);
            }
        }
        return client;
    }

    /**
     * 清理客户端,取得客户端
     *
     * @param config
     */
    public static synchronized OpcUaClient resetClient(OpcTargetBean config) {
        //关闭旧的
        OpcUaClient client = clientConfigMap.remove(config.getId());
        if (client != null) {
            try {
                client.disconnect();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return getClient(config);
    }


    /**
     * 现场内缓存数据连接
     */
    private static ThreadLocal<Connection> tlMap = new ThreadLocal<>();

    /**
     * 取得连接
     *
     * @param configBean
     * @return
     */
    public static Connection getConn(OpcTargetBean configBean) {

        try {
            //加载驱动
            Connection connection = tlMap.get();
            if (connection == null || connection.isClosed()) {
                Class.forName(configBean.getDbDriver());
                connection = DriverManager.getConnection(configBean.getDbUrl(), configBean.getDbUsername(), configBean.getDbPassword());
                tlMap.set(connection);
            }
            return connection;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }


    //表名，列的集合
    private static Map<String, List<String>> tableInfoCache = new HashMap<>();

    /**
     * 取得表列计划
     *
     * @return
     */
    public static Map<String, List<String>> getTableInfoCache() {
        return tableInfoCache;
    }
}
